const regeneratorRuntime = require('../../../utils/runtime.js')
const $ = require('../../../utils/util.js')
import { config } from '../../../utils/config.js'
var api = require('../../../utils/api.js')
import BluetoothLock_lxd_a from '../../../utils/lock_lxd_a.js';
const app = getApp()
var Store = app.Store

Page({
  data: {
    _height: 0,
    lock_code: '', // 扫出的码
    devices:[],
    lock:{}
  },

  onLoad: function (options){
    this.setData({
      _height: app.data._height
    });
  },

  onReady: function (e) {
    // this.mapCtx = wx.createMapContext('map')
  },
 
  onShow: function () {
  
  },
  arrayBufferToStringManual(buffer) {
    let str = '';
    const view = new Uint8Array(buffer);
    for (let i = 0; i < view.length; i++) {
      str += String.fromCharCode(view[i]);
    }
    return str;
  },
  searchBluetooth() {
    wx.openBluetoothAdapter({
      success: () => this.startBluetoothSearch(),
      fail: (err) => {
        console.error("无法初始化蓝牙适配器", err);
        wx.showToast({ title: '蓝牙初始化失败', icon: 'none' });
      }
    });
  },

  startBluetoothSearch() {
    this.setData({
      devices: []
    });
    wx.stopBluetoothDevicesDiscovery({
      success: () => {
        console.log('停止搜索成功');
      },
      fail: (err) => {
        console.log('停止搜索失败', err);
      }
    });
    wx.startBluetoothDevicesDiscovery({
      services: [],
      allowDuplicatesKey: false,
      success: (res) => {
        console.log("开始搜索蓝牙设备",res);
         // 监听发现的设备
        wx.onBluetoothDeviceFound((res) => {
          if (res.devices.length&&res.devices[0].name.length>6) {
            let advertisData =Array.prototype.slice.call(new Uint8Array(res.devices[0].advertisData)).slice(2,8).join(',');
            console.log(advertisData)
            const devices = res.devices.map((item)=>{
              return {...item,advertisData}
            });
            console.log("发现蓝牙设备：", devices);
            this.setData({
              devices: this.data.devices.concat(devices) // 将找到的设备添加到设备列表中
            });
          }
        });
      },
      fail: (err) => {
        console.error("蓝牙设备搜索失败", err);
        wx.showToast({ title: '设备搜索失败', icon: 'none' });
      }
    });
  },
  connectBluetooth(e){
    const deviceId = e.currentTarget.dataset.deviceid;
    const deviceName = e.currentTarget.dataset.devicename;
    wx.setStorageSync('lockName', deviceName);
    // 创建蓝牙连接
    
    wx.openBluetoothAdapter({
      success: () => {
        if(this.isConnected)this.disconnect(deviceId)
        this.setData({
          "lockType":3,//龙兄弟锁 A版协议
          "lock":new BluetoothLock_lxd_a(deviceId),
        });
        setTimeout(()=>{
          wx.createBLEConnection({
            deviceId: deviceId,
            success: (res) => {
              console.log("连接成功：", res);
              wx.showToast({ title: '连接成功', icon: 'success' });
              this.setData({ isConnected: true });
              // 设置连接的设备信息
              this.setData({
                connectedDevice: deviceId,
                // connectedDeviceName: deviceName || '未知设备',
              });
              
              this.connect(deviceId);
            },
            fail: (err) => {
              console.error("连接失败", err);
              wx.showToast({ title: '连接失败', icon: 'none' });
              this.setData({
                isConnected: false,
                connectedDeviceName: null
              });
            }
          });
        },1000)
        
      },
      fail: (err) => {
        console.error("无法初始化蓝牙适配器", err);
        wx.showToast({ title: '蓝牙初始化失败', icon: 'none' });
      }
    });
    
  },
  connect(deviceId){
    this.setData({
      "serviceId": this.data.lock.serviceId, // 蓝牙服务ID
      "characteristicId": this.data.lock.characteristicId, // 特征值ID
      "wcharacteristicId": this.data.lock.wcharacteristicId, // 监听特征值的ID
    })
    var serviceId= this.data.lock.serviceId;// 蓝牙服务ID

    var characteristicId= this.data.lock.wcharacteristicId;// 监听特征值的ID
    console.log("wcharacteristicId",characteristicId)
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: (serRes) => {
        console.log('获取设备服务成功', serRes.services);
        // 假设你知道要使用的服务 UUID，这里可以根据 UUID 进行筛选
        const targetService = serRes.services.find((service) => service.uuid === serviceId);
        if (targetService) {
          this.setData({ serviceId: targetService.uuid });
          wx.getBLEDeviceCharacteristics({
            deviceId: deviceId,
            serviceId: targetService.uuid,
            success: (charRes) => {
              // 假设你知道要使用的特征值 UUID，这里可以根据 UUID 进行筛选
              const targetCharacteristic = charRes.characteristics.find((characteristic) => characteristic.uuid === characteristicId);
              if (targetCharacteristic) {
                this.setData({ characteristicId: targetCharacteristic.uuid });
                wx.notifyBLECharacteristicValueChange({
                  state: true, // 开启通知
                  deviceId,
                  serviceId,
                  characteristicId,
                  success: (res) => {
                    console.log('特征值通知已开启', res);
                    this.data.lock.deviceId=deviceId;
                    this.setStorage(); // 保存连接的设备信息到存储
                    
                    // 监听蓝牙设备特征值变化
                    wx.onBLECharacteristicValueChange((e) => {
                      const receivedData = this.ab2hex(e.value); // 将 ArrayBuffer 转换为字符串
                      console.log('收到蓝牙消息（转换后）：', receivedData);
                      var data= new Uint8Array(e.value);
                      const blueData=this.data.lock.parseBluetoothResponse(data)
                      console.log('接受处理过数据', this.data.lock.parseBluetoothResponse(data))
                      Store.dispatch({
                        type: 'SET_LOCK_DATA',
                        lock_data: this.data.blueData
                      })
                      if(blueData.lvl){
                        app.data.lvl=blueData.lvl
                        this.data.lock.queryLockStatus(wx.getStorageSync("lockToken"))
                        wx.setStorageSync('lvl', blueData.lvl)
                      }
                      if(blueData.locked){
                        wx.setStorageSync('lockeStatus', blueData.locked)
                      }
                      wx.showToast({ title: '监听成功', icon: 'none' })
                      // console.log(app.data.lvl)
                    });
                    $.linkurl('/pages/lockMange/lockHome/lockHome')
                    this.data.lock.getToken();  //5s内未发送消息，锁具会主动断开连接
                  },
                  fail: (err) => {
                    console.error('特征值通知开启失败', err);
                  }
                });
              }
            },
            fail: (err) => {
              console.error('获取设备特征值失败', err);
            },
          });
        }
      },
      fail: (err) => {
        console.error('获取设备服务失败', err);
      },
    });
    
  },

  // ArrayBuffer 转为十六进制字符串
  ab2hex(buffer) {
    return Array.prototype.map.call(new Uint8Array(buffer), bit => ('00' + bit.toString(16)).slice(-2)).join('');
  },

  // 设置本地存储
  setStorage() {
    wx.setStorageSync('lock', JSON.stringify(this.data.lock));
    wx.setStorageSync('lockType', this.data.lockType);
    wx.setStorageSync('blueState', 'connected');
    wx.setStorageSync('blueDevId', this.data.lock.deviceId);
    
    console.log("setStorage");
  },

  // 清空本地存储
  clearStorage() {
    wx.setStorageSync('lock', null);
    wx.setStorageSync('lockType', null);
    // wx.setStorageSync('lockInfo_Tx', null)
    wx.setStorageSync('lockInfo_LXD_A', null)
    wx.setStorageSync('blueDevId', null)
    wx.setStorageSync('blueState', null);
  },

  // 断开蓝牙连接
  disconnect(deviceId,callback) {
   
    wx.closeBLEConnection({
      deviceId: deviceId,
      success: (res) => {
        console.log('断开设备连接成功', res);
        this.setData({ isConnected: false });
        this.clearStorage();
      },
      fail: (err) => {
        // wx.closeBluetoothAdapter() 
        console.error('断开设备连接失败', err);
      },
    });
    wx.closeBluetoothAdapter() 
  },
 




   scanCodeHandle(){ // 扫一扫
    // api.$get(api.main.lockInfo, {
    //   lock_code: '0606180312F3'
    // }).then(resInfo => {
    //   console.log("DDDDDDDDDDDDD"+resInfo)
      
    // })
    this.clearStorage()
    // wx.stopBluetoothDevicesDiscovery({
    //   success: () => {
    //     console.log('停止搜索成功');
    //   },
    //   fail: (err) => {
    //     console.log('停止搜索失败', err);
    //   }
    // });
    wx.scanCode({
      success: async (e) => {
        this.setData({
          lock_code: e.result.replace(/:/g, '')
        })
        console.log(e.result.replace(/:/g, ''), '码扫出来的内容')
        let res = await this._search()
        console.log(res)
        if (res.code == -1) {
          $.toast('该锁没有入库，需先入库')
          setTimeout(() => {
            $.linkurl('/pages/lockMange/chooseSsq/chooseSsq')
          }, 1000)
          Store.dispatch({
            type: 'SET_LOCK_CODE',
            lock_code: this.data.lock_code
          })
        } else if (res && res.code == 0) {
          Store.dispatch({
            type: 'SET_LOCK_CODE',
            lock_code: this.data.lock_code
          })
          $.linkurl('/pages/lockMange/lockHome/lockHome')
        }
      }
    })
  },

  _search() { // 用户是否有权限操作
    return new Promise((resolve, reject) => {
      app.$http.post('/lock/search', {
        lock_code: this.data.lock_code
      }).then(res => {
        if (res) {
          resolve(res)
        }
      })
    })
  }

})
